import Taro from "@tarojs/taro";
import { HTTP_STATUS_CODE } from "@/config/http-status-code";
import { isMock, mockList, mockUrl } from "@/config/mock-config";
import { SENSORS_UTM } from '@/libs/sensorsdata/config';

console.log("process.env.NODE_ENV:", process.env.NODE_ENV);

let base = process.env.BASE_URL;

export default {
  baseOptions(params, method: 'GET' | 'POST' = "GET") {
    let { url, data } = params;
    isMock && mockList.includes(url) && (base = mockUrl);
    /* 统一处理后端埋点传广告参数 */
    if (data && data.needSensor) {
      const sensorData = Taro.getStorageSync(SENSORS_UTM) || {}
      data = {
        ...data,
        needSensor: undefined,
        ...sensorData
      }
    }
    // let token = getApp().globalData.token
    // if (!token) login()
    // console.log('params', params)
    let token = Taro.getStorageSync("token");
    let contentType = "application/x-www-form-urlencoded";
    contentType = params.contentType || contentType;
    let targetServiceName = params.targetServiceName || 'habitformat-season-5-api';
    const option = {
      isShowLoading: false,
      loadingText: "正在加载",
      url: base + url,
      data: data ? JSON.parse(JSON.stringify(data)) : data,
      method: method,
      header: {
        "content-type": contentType,
        "Authorization": token,
        "APP-NAME": "habit-format-mini",
        "APP-VERSION": "2.1.0",
        "Target-Service-Name": targetServiceName,
        "token": token,
      }
    };
    return new Promise((resolve, reject) => {
      Taro.request(option)
        .then(res => {
          switch (res.statusCode) {
            case HTTP_STATUS_CODE.SUCCESS: {
              if (res.data.status_code === HTTP_STATUS_CODE.SUCCESS) {
                return resolve(res.data);
              } else if (
                ~~res.data.status_code === HTTP_STATUS_CODE.AUTHENTICATE
              ) {
                // console.log("登录失效");
                const oldToken = Taro.getStorageSync("token");
                oldToken && Taro.removeStorageSync("token");
                Taro.navigateTo({ url: "/pages/not-login/index" });
                return reject(res.data);
              } else if (
                res.data.status_code === HTTP_STATUS_CODE.ACTIVITY_DELETE
              ) {
                // 活动删除了跳首页
                Taro.showToast({
                  title: res.data.message,
                  icon: "none",
                  duration: 2000
                });
                setTimeout(() => {
                  /* 当前页面是主题详情页面 且是从圈子页面进来的 这种情况返回圈子页面 */
                  const getCurrentPages = Taro.getCurrentPages()
                  const cuurentPotion = getCurrentPages[getCurrentPages.length - 1].route
                  const prvePotion = getCurrentPages[getCurrentPages.length - 2].route
                  if (cuurentPotion === 'package/theme-detail/index' && prvePotion === 'pages/social-circle/index') {
                    Taro.navigateBack({
                      delta: 1
                    })
                  } else {
                    Taro.switchTab({
                      url: "/pages/index/index"
                    });
                  }
                }, 2000);
                return reject(res.data);
              } else {
                return reject(res.data);
              }
            }
            case HTTP_STATUS_CODE.AUTHENTICATE:
              console.log("登录失效");
              /**移除token并跳转登录页 */
              const oldToken = Taro.getStorageSync("token");
              oldToken && Taro.removeStorageSync("token");
              Taro.navigateTo({ url: "/pages/not-login/index" });
              return reject(res.data);
            default:
              return reject(res.data);
          }
        })
        .catch(rej => {
          reject(rej.data);
        });
    });
  },
  get(url, data = "", targetServiceName = "") {
    let option = { url, data, targetServiceName };
    return this.baseOptions(option);
  },
  post: function (url, data, targetServiceName = "", contentType = "application/x-www-form-urlencoded") {
    let params = { url, data, contentType, targetServiceName };
    return this.baseOptions(params, "POST");
  }
};
